import React, { useState,useEffect } from "react";
import {Button, Input, Dropdown, Space, Card, Layout, Modal, Image} from "antd";
import type { MenuProps } from 'antd';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { DownOutlined } from '@ant-design/icons';
import {keyframes} from "antd-style";
import {getLoginUserUsingGet} from "@/services/openAPI-backend/userController";
import { Link, history } from '@umijs/max';
const ChatInterface: React.FC = () => {
    const [chatMode, setChatMode] = useState<string>('Doubao-lite-4k');
    const [chatURL, setChatURL] = useState<string>('https://doubao-function-yufueicshw.cn-hangzhou.fcapp.run/$path');
    const [messages, setMessages] = useState<{ user: string, ai: string }[]>([]);
    const [currentQuestion, setCurrentQuestion] = useState<string>('');
    const messageContainerRef = React.useRef<HTMLDivElement>(null);
    const [isFirstVisit, setIsFirstVisit] = useState(true);
    const [loginUser, setCurrentUser] = useState<API.User>({  });
    const [commitState, setCommitState] = useState<boolean>(false);
    const fadeIn = keyframes`
        from {
            opacity: 0;
            transform: translateY(100%); /* 初始位置在屏幕下方100% */
        }
        to {
            opacity: 1;
            transform: translateY(0); /* 结束位置在正常位置 */
        }
`;
    const getLoginUser = async () => {
        try {
            const res = await getLoginUserUsingGet();

            setCurrentUser(res?.data);
        }catch (e) {
            history.push('/user/login')
        }
    };
    let buffer = "";
    React.useEffect(() => {
        // 当messages状态更新时，尝试滚动到底部
        const scrollToBottom = () => {
            if (messageContainerRef.current) {
                messageContainerRef.current.scrollTop = messageContainerRef.current.scrollHeight;
            }
        };

        scrollToBottom();
    }, [messages]); // 依赖于messages数组的变化来触发

    const ModeExchange = (url:string,mode:string) =>{
        setChatMode(mode);
        setChatURL(url);
    }
    const cleanChat = () =>{
        Modal.confirm({
            title: '提示',
            content: '是否清空chat记录？',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                setMessages([]);
            },
        });
    }
    const sendMessage = async () => {
        if (currentQuestion.trim()) {
            if (isFirstVisit) {
                setIsFirstVisit(false);
            }
            setMessages(prevMessages => [...prevMessages, { user: currentQuestion, ai: '' }]);
            setCurrentQuestion('');

            try {
                const controller = new AbortController();
                const { signal } = controller;
                setCommitState(true);
                await fetchEventSource(chatURL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ question: currentQuestion }),
                    signal,
                    onmessage(event) {
                        if (event.data !== 'done') {
                            setMessages(prevMessages => {
                                const updatedMessages = [...prevMessages];
                                const lastMessageIndex = updatedMessages.length - 1;
                                updatedMessages[lastMessageIndex].ai += event.data;
                                return updatedMessages;
                            });
                        }
                    },
                    onerror(error) {
                        console.error("Error fetching stream:", error);
                    },
                });
                setCommitState(false)
            } catch (error) {
                if (error.name === 'AbortError') {
                    console.log('Fetch cancelled');
                } else {
                    console.error(error);
                }
            }
        }
    };
    const items: MenuProps['items'] = [
        {
            label: (
                <a target="_blank" rel="noopener noreferrer" onClick={()=>{ModeExchange('https://doubao-function-yufueicshw.cn-hangzhou.fcapp.run/$path','Doubao-lite-4k')}}>
                    Doubao-lite-4k(默认)
                </a>
            ),
            key: '0',
        },
        {
            label: (
                <a target="_blank" rel="noopener noreferrer" onClick={()=>{ModeExchange('https://doubao-function-akkvppaxrj.cn-hangzhou.fcapp.run/$path','Doubao-pro-4k')}}>
                    Doubao-pro-4k(性能更强)
                </a>
            ),
            key: '1',
        },
        {
            label: (
                <a target="_blank" rel="noopener noreferrer" onClick={()=>{ModeExchange('https://tongyi-function-yupufncqbw.cn-hangzhou.fcapp.run/$path','qwen-plus')}}>
                    qwen-plus
                </a>
            ),
            key: '2',
        },
        {
            label: (
                <a target="_blank" rel="noopener noreferrer" onClick={()=>{ModeExchange('https://qianfanfunction-qdigoflakd.cn-hangzhou.fcapp.run/$path','ERNIE-4.0-8K-Latest')}}>
                    ERNIE-4.0-8K-Latest
                </a>
            ),
            key: '3',
            disabled: loginUser.userRole ==='admin'? false : true,
        },
    ];
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setCurrentQuestion(e.target.value);
    };
    useEffect(() => {
        getLoginUser();
    }, []);
    return (
        <Layout>
            <Card extra={<>
                <Dropdown menu={{items}}>
                    <a onClick={(e) => e.preventDefault()}>
                        <Space>
                            {chatMode}
                            <DownOutlined/>
                        </Space>
                    </a>
                </Dropdown>
                <Button disabled={commitState} size={'middle'} style={{marginLeft: '10px',borderRadius: '24px'}} type="primary" onClick={() => {
                    cleanChat()
                }}>清空</Button> {/* 添加具体的按钮类型和文本 */}
            </>} ref={messageContainerRef} title={<h2 style={{marginTop: '10px'}}>E-GPT</h2>} style={{
                width: '100%',
                height: '80vh',
                boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
                borderRadius: '10px',
                overflow: 'auto'
            }}>
                {isFirstVisit && (
                    <div style={{
                        textAlign: 'center',
                        marginBottom: '16px',
                        fontSize: '14px',
                        color: '#666',
                        marginTop: '5%',
                        animation: `${fadeIn} 0.5s ease-in-out forwards`,
                    }}>
                        欢迎使用E-GPT！我是您的专属平台顾问，基于平台数据精调，能为您提供专业、个性化的咨询服务。请随时向我提问。
                        <Image
                            src={'https://tse4-mm.cn.bing.net/th/id/OIP-C.ox3_Y53WCiCfQ778oXVarQHaI_?w=198&h=241&c=7&r=0&o=5&pid=1.7\''}
                            preview={false}></Image></div>

                )}
                <div style={{
                    marginBottom: "60px",
                    position: 'relative',
                    height: 'calc(100% - 64px)',
                    overflowY: 'auto',
                    padding: '20px',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '16px'
                }}>
                    {messages.map((msg, index) => (
                        <div key={index} style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
                            {/* 用户问题 */}
                            <div style={{
                                boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
                                alignSelf: 'flex-end',
                                backgroundColor: '#DCF8C6',
                                padding: '12px',
                                borderRadius: '16px',
                                maxWidth: '75%',
                                wordBreak: 'break-word',
                                animation: `${fadeIn} 0.5s ease-in-out`
                            }}>
                                {msg.user}
                            </div>
                            {/* AI回答 */}
                            <div style={{
                                boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
                                alignSelf: 'flex-start',
                                backgroundColor: '#F0F0F0',
                                padding: '12px',
                                borderRadius: '16px',
                                maxWidth: '75%',
                                wordBreak: 'break-word',
                                animation: `${fadeIn} 0.5s ease-in-out`
                            }}>
                                {msg.ai}
                            </div>
                        </div>
                    ))}
                </div>

            </Card>
            <div style={{
                animation: `${fadeIn} 0.5s ease-in-out forwards`,
                borderRadius: '10px',
                border: "none",
                zIndex: 1,
                display: 'flex',
                padding: '20px',
                position: 'relative',
                bottom: "8%",
                width: '100%',
            }}>
                <Input
                    value={currentQuestion}
                    onChange={handleInputChange}
                    onPressEnter={sendMessage}
                    placeholder="请输入您的问题..."
                    style={{flex: 1, marginRight: '16px',height: '40px'}}
                    showCount="true"

                />
                <Button disabled={commitState} type="primary" onClick={sendMessage} style={{borderRadius: '24px',height: '40px'}}>发送</Button>
            </div>
        </Layout>
    );
};

export default ChatInterface;